package cn.touna.jss.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

@SuppressWarnings("deprecation")
public class CommonHttpInvoke {
    public static String getUrl(String systemTag, String method) {
        String url = "";
        if ("localhost".equals(systemTag.toLowerCase())) {
            url = Constants.GS_URL_MY;
        }
        if ("dev".equals(systemTag.toLowerCase())) {
            url = Constants.GS_URL_DEV;
        }
        url = url + method;
        return url;
    }

    public static void jsonHttpPost(String url, Object requestObject) throws IOException {
        long starTime = System.currentTimeMillis();
        HttpURLConnection connection = URLConnection.getConnection(url);
        DataOutputStream out = null;
        connection.setRequestProperty("content-timestamp", String.valueOf(starTime));
        connection.setRequestProperty("content-md5", Common.getSign((requestObject.toString()), String.valueOf(starTime)));
        connection.connect();
        out = new DataOutputStream(connection.getOutputStream());
        out.write(requestObject.toString().getBytes("utf-8"));
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        connection.disconnect();
        long endTime = System.currentTimeMillis();
        long Time = endTime - starTime;
        if (Time > 10000) {
            System.out.println(Time + "------------------超过10秒");
        } else if (Time > 2000) {
            System.out.println(Time + "------------------超过2秒");
        } else if (Time > 1000) {
            System.out.println(Time + "------------------超过1秒");
        }
    }


    public static void webJsonHttpPost(String url, Object requestObject, String loginKey, String loginVal) throws IOException {

        long starTime = System.currentTimeMillis();
        HttpURLConnection connection = URLConnection.getConnection(url);
        DataOutputStream out = null;
        connection.setRequestProperty("content-md5", loginKey + "," + Common.MD5(requestObject.toString() + loginVal));
        connection.connect();
        out = new DataOutputStream(connection.getOutputStream());
        out.write(requestObject.toString().getBytes("utf-8"));
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        connection.disconnect();
        long endTime = System.currentTimeMillis();
        long Time = endTime - starTime;
        if (Time > 10000) {
            System.out.println(Time + "------------------超过10秒");
        } else if (Time > 2000) {
            System.out.println(Time + "------------------超过2秒");
        } else if (Time > 1000) {
            System.out.println(Time + "------------------超过1秒");
        }
    }

    public static String multipartHttpPost(String url, SortedMap<String, Object> sortedParams, String file_url) {
        HttpClient client = new DefaultHttpClient(new ThreadSafeClientConnManager());
        HttpPost httppost = new HttpPost(url);
        long starTime = System.currentTimeMillis();
        try {
            FileBody bin = new FileBody(new File(file_url));

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("file", bin);
            StringBuffer sb = new StringBuffer();
            Set es = sortedParams.entrySet();
            Iterator it = es.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String k = (String) entry.getKey();
                Object v = entry.getValue();
                if (null != v && !"".equals(v)
                        && !"sign".equals(k) && !"key".equals(k)) {
                    sb.append(k + "=" + v + "&");
                    reqEntity.addPart(k, new StringBody(v.toString()));
                }
            }
            String generateMD5 = Common.MD5(sb.toString()).toUpperCase();

            httppost.setEntity(reqEntity);
            httppost.setHeader("content-md5", generateMD5);

            HttpResponse response = client.execute(httppost);
            System.out.println("请求接口返回状态：" + response.getStatusLine().getStatusCode());
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println(EntityUtils.toString(entity));
                }
            }
            long endTime = System.currentTimeMillis();
            long Time = endTime - starTime;
            if (Time > 10000) {
                System.out.println(Time + "------------------超过10秒");
            } else if (Time > 2000) {
                System.out.println(Time + "------------------超过2秒");
            } else if (Time > 1000) {
                System.out.println(Time + "------------------超过1秒");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client.getConnectionManager().shutdown();
        }
        return null;
    }
}
